package com.feonix.blockchain.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.feonix.blockchain.dao.BlockChain;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/nodes")
public class NodesController {

    // 注册节点
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json")
    public String register(@RequestBody String jsonParam) throws MalformedURLException {
        Map<String, Object> result = new HashMap<String, Object>();

        JSONObject jsonObject = JSON.parseObject(jsonParam);
        List<String> addresses = jsonObject.getJSONArray("addresses").toJavaList(String.class);

        // 对获取到的节点地址集合判断是否为空
        if (addresses == null) {
            result.put("message", "Error: Please supply a valid list of nodes");
            return JSON.toJSONString(result);
        }

        // 注册节点
        BlockChain blockChain = BlockChain.getInstance();
        for (String address : addresses) {
            blockChain.registerNode(address);
        }

        // 向客户端返回处理结果
        result.put("message", "New nodes have been added");
        result.put("registered_nodes", blockChain.getNodes().toArray());

        return JSON.toJSONString(result);
    }

    // 解决冲突
    @RequestMapping("/resolve")
    public String resolve() throws IOException {
        BlockChain blockChain = BlockChain.getInstance();
        boolean resolved = blockChain.resolveConflicts();

        Map<String, Object> result = new HashMap<String, Object>();
        if (resolved) {
            result.put("message", "Our chain was replaced");
            result.put("new_chain", blockChain.getChain());
        } else {
            result.put("message", "Our chain is authoritative");
            result.put("chain", blockChain.getChain());
        }

        return JSON.toJSONString(result);
    }
}
